import { ref } from 'vue'
import { defineStore } from 'pinia'

import api from '@/api/order'
import { type PageInfo } from '@/config/types'
import cfg from '@/config/config'
import type { OrderCreateForm, OrderSearchForm } from '@/config/form'
import type { OrderListItem, OrderDetail } from '@/config/types'

export const useOrderStore = defineStore('orderStore', () => {
  const loading = ref<boolean>(false)
  const orderList = ref<OrderListItem[]>([])
  const searchForm = ref<OrderSearchForm>({
    status: 1,
    page: 1,
    limit: cfg.pageSize
  })
  const pageInfo = ref<PageInfo>({
    page: 1,
    limit: cfg.pageSize,
    total: 0
  })

  const order = ref<OrderDetail>({
    id: 0,
    orderNo: '',
    lessonId: 0,
    status: 0,
    price: 0,
    title: '',
    thumb: '',
    createdAt: 0
  })

  async function searchList() {
    loading.value = true
    try {
      const res = await api.searchList(searchForm.value)
      orderList.value = res.data
      pageInfo.value = {
        page: res.page,
        limit: res.size,
        total: res.total
      }
    } finally {
      loading.value = false
    }
  }

  function changePage(page: number) {
    searchForm.value.page = page
    searchList()
  }

  function changeTab(status: number | null) {
    searchForm.value.page = 1
    searchForm.value.status = status == -1 ? null : status
    searchList()
  }

  async function getOrder(no: string) {
    loading.value = true
    try {
      const res = await api.detail(no)
      order.value = res.data
      console.log(no, order.value)
    } finally {
      loading.value = false
    }
  }

  async function cancel(id: number) {
    loading.value = true
    let result: boolean
    try {
      const res = await api.cancel(id)
      result = res.data
    } catch (e) {
      result = false
    } finally {
      loading.value = false
    }
    return result
  }

  async function create(form: OrderCreateForm) {
    loading.value = true
    let orderno: string
    try {
      const res = await api.create(form)
      orderno = res.data
    } catch (e) {
      orderno = ''
    } finally {
      loading.value = false
    }
    return orderno
  }

  return {
    loading,
    orderList,
    searchForm,
    pageInfo,
    order,

    searchList,
    changePage,
    changeTab,
    getOrder,
    cancel,
    create
  }
})
